using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class SimpleFellowCamera : MonoBehaviour
{
    public Camera cam;
    public float distance = 10f;
    public float offset = 1.0f;
    public float rotY;
    public float rotX = 20;

    public float minRotX = -20;
    public float maxRotX = 20;
    public Transform target;
    public bool isLocal = false;

    public LayerMask hitMask = -1;
    public bool isLock = false;
    public Vector3 lockOffet;
    void Start()
    {
        if (null == cam)
            cam = Camera.main;
    }

    // Update is called once per frame
    void LateUpdate()
    {
        if (null == target || null == cam)
        {
            return;
        }
        if (isLock)
        {
            cam.transform.position = target.transform.position + lockOffet;
        }
        Vector3 dir = Vector3.back * distance;
        dir = Quaternion.Euler(rotX, rotY, 0) * dir;
        if(isLocal)
            dir = transform.localToWorldMatrix.MultiplyVector(dir);
        var pos = this.transform.position  + Vector3.up * offset;
        if (hitMask == 0)
        {
            cam.transform.position = pos  + dir;
        }
        else
        {
            RaycastHit hit;
            if (Physics.Raycast(pos, dir, out hit, distance, hitMask))
            {
                cam.transform.position = pos+ dir.normalized*(hit.distance-0.1f);
            }
            else
            {
                cam.transform.position = pos  + dir;
            }
        }
        cam.transform.forward = -dir;
        lockOffet = cam.transform.position - target.position;
    }

    internal void FixData()
    {
        if (rotX < minRotX)
        {
            rotX = minRotX;
        }
        if (rotX > maxRotX)
        {
            rotX = maxRotX;
        }
    }
}
